import type { Directive, DirectiveBinding, ObjectDirective } from "vue";

interface MenuItem {
  text: string;
  action: () => void;
}

type MenuItems = MenuItem[];

const rightMenuDirective: ObjectDirective = {
  mounted(el, binding) {
        const menuItems: MenuItems = binding.value;
        const menu = document.createElement("ul");
        menu.classList.add("context-menu");
        menuItems.forEach((item) => {
          const menuItem = document.createElement("li");
          menuItem.innerHTML = item.text;
          menuItem.addEventListener("click", () => item.action());
          menu.appendChild(menuItem);
        });

        const handler = (e: MouseEvent) => {
          e.preventDefault();
          const menuItems: MenuItems = binding.value;
          const menu = document.createElement("ul");
          const body = document.body;
        
          body.style.height = "100%";
          body.style.overflow = "hidden"; // 防止菜单滚动时与页面的滚动产生冲突
          menu.style.position = "fixed";
          menu.style.top = "50%";
          menu.style.left = "50%";
          menu.style.transform = "translate(-50%, -50%)";
          menu.style.zIndex = "999";
        
          menu.classList.add("context-menu");
          menuItems.forEach((item) => {
            const menuItem = document.createElement("li");
            menuItem.innerHTML = item.text;
            menuItem.addEventListener("click", () => {
              item.action();
              body.style.height = "";
              body.style.overflow = "";
              menu.remove();
            });
            menu.appendChild(menuItem);
          });
        
          body.appendChild(menu);
        
          document.addEventListener(
            "click",
            () => {
              body.style.height = "";
              body.style.overflow = "";
              menu.remove();
            },
            { once: true } // 添加 once 选项以防止多次触发
          );
        };

        el.addEventListener("contextmenu", handler);
        el.__right_click_menu_handler__ = handler;

        document.addEventListener("click", () => {
          const menu = document.querySelector(".context-menu");
          if (menu) {
            menu.remove();
          }
        });
  },
  beforeUnmount(el: HTMLElement) {
   el.removeEventListener("contextmenu", el.__right_click_menu_handler__);
  }
};

function getMousePosition(e: MouseEvent) {
  const { clientX, clientY } = e;
  const { scrollLeft, scrollTop } = document.documentElement;
  return {
    x: clientX + scrollLeft,
    y: clientY + scrollTop
  };
}

export default rightMenuDirective as Directive;

